package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("QuantitytypeService")
@Transactional

public class QuantitytypeServiceImpl extends CmiEmaService implements QuantitytypeService {
	public QuantitytypeServiceImpl() {
	}

	@Transactional
	public Quantitytype saveQuantitytype(Quantitytype quantitytype) {
		Set<Eventquantitytype> existingEventquantitytypesForQuantitytype = new HashSet<Eventquantitytype>();

		Set<Eventquantitytype> selectedEventquantitytypesForQuantitytype = quantitytype
				.getEventquantitytypesForQuantitytype();

		if (quantitytype.getId() == null) {

			Quantitytype existingQuantitytype = quantitytypeDAO
					.findQuantitytypeByPhysicalPrimaryKey(quantitytype.getName());

			if (isEquals(quantitytype, existingQuantitytype)) {
				return existingQuantitytype;
			}

			quantitytype = quantitytypeDAO.store(quantitytype);
			quantitytypeDAO.flush();

			for (Eventquantitytype relatedEventquantitytype : selectedEventquantitytypesForQuantitytype) {
				relatedEventquantitytype.setQuantitytype(quantitytype);
				eventquantitytypeDAO.store(relatedEventquantitytype);
			}
		} else {
			Quantitytype existingQuantitytype = quantitytypeDAO.findQuantitytypeByPrimaryKey(quantitytype.getId());

			existingEventquantitytypesForQuantitytype = existingQuantitytype.getEventquantitytypesForQuantitytype();

			Set<Eventquantitytype> prepareDeleteEventquantitytypesForQuantitytype = new HashSet<Eventquantitytype>();
			Set<Eventquantitytype> prepareAddEventquantitytypesForQuantitytype = new HashSet<Eventquantitytype>();

			prepareDeleteEventquantitytypesForQuantitytype.addAll(selectedEventquantitytypesForQuantitytype);
			prepareDeleteEventquantitytypesForQuantitytype.addAll(existingEventquantitytypesForQuantitytype);

			prepareAddEventquantitytypesForQuantitytype.addAll(selectedEventquantitytypesForQuantitytype);
			prepareAddEventquantitytypesForQuantitytype.addAll(existingEventquantitytypesForQuantitytype);

			prepareDeleteEventquantitytypesForQuantitytype.removeAll(selectedEventquantitytypesForQuantitytype);
			prepareAddEventquantitytypesForQuantitytype.removeAll(existingEventquantitytypesForQuantitytype);

			for (Eventquantitytype relatedEventquantitytype : prepareAddEventquantitytypesForQuantitytype) {
				relatedEventquantitytype.setQuantitytype(quantitytype);
				eventquantitytypeDAO.store(relatedEventquantitytype);
			}

			for (Eventquantitytype relatedEventquantitytype : prepareDeleteEventquantitytypesForQuantitytype) {
				relatedEventquantitytype.setQuantitytype(null);
				eventquantitytypeDAO.store(relatedEventquantitytype);
			}
			quantitytype = quantitytypeDAO.store(quantitytype);
			quantitytypeDAO.flush();
		}

		eventquantitytypeDAO.flush();
		return quantitytype;
	}

	public void deleteQuantitytype(Quantitytype quantitytype) {
		quantitytypeDAO.remove(quantitytype);
		quantitytypeDAO.flush();
	}

	@Transactional
	public void deleteQuantitytypes(Set<Integer> deleteQuantitytypesId) {
		Query query = quantitytypeDAO.createNamedQuery("deleteQuantitytypesById", -1, -1);
		query.setParameter(1, deleteQuantitytypesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Quantitytype> loadQuantitytypes() {
		return quantitytypeDAO.findAllQuantitytypes();

	}

	@Transactional
	public Set<Quantitytype> loadReferenceQuantitytypes(Set<Quantitytype> quantitytypes) {
		Iterator<Quantitytype> quantitytypesIterator = quantitytypes.iterator();
		Set<Quantitytype> referencedQuantitytypes = new HashSet<>();
		while (quantitytypesIterator.hasNext()) {
			Quantitytype currentQuantitytype = quantitytypesIterator.next();

			if (!currentQuantitytype.getEventquantitytypesForQuantitytype().isEmpty()) {
				referencedQuantitytypes.add(currentQuantitytype);
				continue;
			}
		}
		return referencedQuantitytypes;
	}

	public Set<Quantitytype> loadQuantitytypesByIdSet(Set<Integer> quantitytypeIdSet) {

		Iterator<Integer> quantitytypeIdIterator = quantitytypeIdSet.iterator();
		Set<Quantitytype> quantitytypeSet = new HashSet<>();
		while (quantitytypeIdIterator.hasNext()) {
			Integer id = quantitytypeIdIterator.next();
			Quantitytype currentQuantitytype = quantitytypeDAO.findQuantitytypeById(id);
			quantitytypeSet.add(currentQuantitytype);
		}
		return quantitytypeSet;
	}

	@Transactional
	public List<Quantitytype> findAllQuantitytypes(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Quantitytype>(quantitytypeDAO.findAllQuantitytypes(startResult, maxRows));
	}

	@Transactional
	public Quantitytype findQuantitytypeByPrimaryKey(Integer id) {
		return quantitytypeDAO.findQuantitytypeByPrimaryKey(id);
	}

	@Transactional
	public Integer countQuantitytypes() {
		return ((Long) quantitytypeDAO.createQuerySingleResult("select count(o) from Quantitytype o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countQuantitytypes(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Quantitytype.class);
		return ((Long) quantitytypeDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countQuantitytypesByName(String queryName) {
		Query query = quantitytypeDAO.createNamedQuery("countQuantitytypesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countQuantitytypesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Quantitytype.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadQuantitytypeObjectReferencedSet(Quantitytype quantitytype) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> eventquantitytypesIds = new HashSet<Integer>();
		for (Eventquantitytype obj : quantitytype.getEventquantitytypesForQuantitytype()) {

			eventquantitytypesIds.add(obj.getId());
		}
		objectReferencedSetMap.put("eventquantitytypesIds", eventquantitytypesIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadQuantitytypeClassReferencedSet(Quantitytype quantitytype) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("eventquantitytypes", eventquantitytypeDAO.findAllEventquantitytypes());

		return classReferencedSetMap;
	}

	public boolean isEquals(Quantitytype quantitytype, Object obj) {
		if (obj == quantitytype)
			return true;
		if (!(obj instanceof Quantitytype))
			return false;
		Quantitytype comparedQuantitytype = (Quantitytype) obj;
		if (!CheckPropertyEqual(quantitytype.getName(), comparedQuantitytype.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

